package com.baibei.ebec.moments.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.model.UserInfo;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BBSEditorActivity extends AppCompatActivity {

    @BindView(R2.id.iv_back)
    ImageView ivBack;
    @BindView(R2.id.tv_send)
    TextView tvSend;
    @BindView(R2.id.et_bbs)
    EditText etBbs;
    private int userId;
    private String resp;
    private String contents;
    private static final int CAMERA_PIC = 1;
    private static final int ALBUM_PIC = 2;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbseditor);
        ButterKnife.bind(this);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            initPhotoError();
        }
        UserInfo user = SessionManager.getDefault().getUser();
        userId = user.getUserId();

        file = new File("/mnt/sdcard/pic/01.jpg");
    }

    @OnClick(R2.id.iv_back)
    public void onFinishClicked() {
        IsRealFinish();
    }

    @Override
    public void onBackPressed() {
        IsRealFinish();
    }

    public void IsRealFinish() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定要退出吗?")
                .setMessage("未发送内容将不会被保存")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        BBSEditorActivity.this.finish();
                    }
                }).create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.GRAY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        AppUI.dismiss();
    }

    @OnClick(R2.id.tv_send)
    public void onSendClicked() {
        contents = etBbs.getText().toString().trim();
        if ("".equals(contents)) {
            ToastUtils.showShortToast("发帖内容不能为空");
            return;
        }
        AppUI.loading(this);
        new Thread(new Runnable() {

            @Override
            public void run() {
                String url = ApiConstant.API_BASE_URL + "ddq/api/v1/article/addArticle";
                HashMap<String, Object> map = new HashMap<>();
//                File file = new File("");
                map.put("userId", (long) userId);
                map.put("contents", contents);
//                map.put("myfiles",file);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    AppUI.dismiss();
                    resp = response.body().string();
                    Log.i("resphh", resp);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            afterSend();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void afterSend() {
        try {
            JSONObject jsonObject = new JSONObject(resp);
            ToastUtils.showShortToast(jsonObject.optString("message"));
            if ("0".equals(jsonObject.optString("code"))) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("state", "success");
                intent.putExtras(bundle);
                setResult(2, intent);
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R2.id.iv_camera)
    public void onCameraClicked() {
        File file = new File(Environment.getExternalStorageDirectory(), "tempImg.jpg");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,CAMERA_PIC);
    }

    @OnClick(R2.id.iv_pic)
    public void onPicClicked() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,ALBUM_PIC);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initPhotoError(){
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case ALBUM_PIC:
                if (resultCode == RESULT_OK){
                    Uri imgUri = data.getData();
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(imgUri, filePath, null, null, null);
                    int columnIndex = cursor.getColumnIndex(filePath[0]);
                    String path = cursor.getString(columnIndex);
                    cursor.close();
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                }
        }
    }

    private void bitmapToFile(Bitmap bitmap){
        file.delete();
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            fos.flush();
            bitmap.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
